#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
Created on 2012/02/7

Module with the class that creates a bar or pie chart graphics and displays it in a new window
    using the QT4Agg backend from pyqt.

Requires pyqt to run

From terminal run:
    apt-cache search pyqt
    sudo apt-get install python-qt4

Based on : http://matplotlib.sourceforge.net/examples/api/barchart_demo.html
    and http://matplotlib.sourceforge.net/examples/pylab_examples/pie_demo.html

@author: João Vitor Machado Batista nº 5479
'''

import matplotlib
matplotlib.use('QT4Agg')
from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.backends.backend_qt4agg import NavigationToolbar2QTAgg as NavigationToolbar

import random
import matplotlib.pyplot as plot
import numpy as np

class Graphics():

    def graficCreation(self, yearArray, valuesArray, plotLabelX, plotLabelY, plotTitle, plotType):
        '''
            creates a graphic with the given parameters
        '''


        N = len(yearArray)

        ind = np.arange(N)
        widthB = 0.8
        
        label = []
        colores = []
        explode = []
        
        for y in range(0, len(yearArray)):
            
            if(plotType == 'pie'):
                DataString = '''Y:{0} | Q:{1}'''.format(yearArray[y], valuesArray[y])
                label.append(DataString)
                explode.append(0.05)
                pass
                        
            colores.append([random.random(), random.random(), random.random()])
            
            pass

        if(plotType == 'bar'):
                      
            rects = plot.bar(ind, valuesArray, width = widthB, bottom = 0,
                             color=colores, xerr = 0, yerr = 0)
            
            plot.xticks(ind+(widthB/2), yearArray)
            
            plot.xlabel(plotLabelX)
            plot.ylabel(plotLabelY)
            
            plot.grid(True)

            self.autolabel(rects, valuesArray)
            
            pass

        if(plotType == 'pie'):

            plot.pie(valuesArray, labels = label, shadow = True, explode = explode, colors = colores)

            pass

        plot.title(plotTitle)
        plot.show()
        pass

    def autolabel(self, rects, valuesArray):
        '''
            add's the result in the top of a bar chart
        '''
        i = 0
        for rect in rects:
            height = rect.get_height()
            plot.text(rect.get_x()+rect.get_width()/2.,
                      1.005*height,
                      '%s'%(valuesArray[i]),
                      ha='center', va='bottom')
            i = i + 1
            pass
        pass
        
